package com.starblink.home.ui.part

//import com.starblink.home.ui.adapter.ScrollFirstProductHelper

import android.app.Activity
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.brv.utils.models
import com.starblink.android.basic.ext.bindProductFeeds
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.toastShowDev
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.basic.autosize.utils.AutoSizeUtils
import com.starblink.basic.ext.screenHeight
import com.starblink.discover.util.ScrollCalculatorHelper2Home
import com.starblink.home.R
import com.starblink.home.databinding.*
import com.starblink.home.ui.NavHomeVM
import com.starblink.home.ui.bean.RvFeedsBrandCollBean
import com.starblink.home.ui.bean.RvFeedsProductBean
import com.starblink.home.ui.bean.RvFeedsWeatherVaneBean
import com.starblink.home.ui.cells.*
import com.starblink.library.widget.databinding.CellSimpleProductCardBinding
import com.starblink.library.widget.loading.GoodsCardLoadingCell


/**
 * 处理feeds流的事件 风向标 商品合集 运营推荐 及feeds的骨架/空界面
 */
class PartFeeds(
    var activity: Activity,
    var viewBinding: FragmentNavHomeBinding,
    var viewModel: NavHomeVM,
    var homeApiResultControl: HomeApiResultControl
) {
    var layoutManager: StaggeredGridLayoutManager? = null


    private val feedsAdapter: MutableAdapter by lazyOnNone {

        MutableAdapter(viewModel.feedsObserveData.value!!).apply {
            //初始化loading
            addVhDelegate {
                SkeletonCell(
                    LayoutHomeSkeletonFeedsBinding.inflate(it.inflater, it, false)
                )
            }
            //noData
            addVhDelegate {
                EmptyCell(
                    LayoutFeedsEmptyBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                FeedsBannerCell(
                    LayoutHomeFeedsOperSelectBannerBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                FeedsGifCell(
                    LayoutHomeFeedsOperSelectGifBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                FeedsVideoCell(
                    activity,
                    LayoutHomeFeedsOperSelectVideoBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                ProductCell(
                    activity,
                    refreshStateView = viewBinding.page,
                    recyclerView = viewBinding.navHomeRv,
                    viewBinding.navHomeRv,
                    scrollCalculatorHelper,
                    CellSimpleProductCardBinding.inflate(it.inflater, it, false),
                    cardClick = { md, position ->
                        handleFeedsClick(md, position)
                    }
                )
            }
            addVhDelegate {
                VaneCell(
                    activity,
                    LayoutHomeFeedsVaneBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                BrandCollCell(
                    LayoutHomeFeedsBrandCollBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                FeedsDiscountCollectionMultiBrandCell(
                    activity,
                    LayoutHomeFeedsDiscountMultiBrandBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                FeedsDiscountCollectionSingleBrandCell(
                    activity,
                    LayoutHomeFeedsDiscountSingleBrandBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                FeedsDiscountCollectionSubscribeMerchantCell(
                    activity,
                    LayoutHomeFeedsDiscountSubscribeMerchantBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                FeedsDiscountCollectionSingleCategoryCell(
                    activity,
                    LayoutHomeFeedsDiscountSingleCategoryBinding.inflate(it.inflater, it, false)
                )
            }

        }
    }


    fun dataChange(it: ArrayList<Any>) {
        //首页情况比较特殊 骨架和空布局在feeds流里 所以加了一些各种判断
//            viewBinding.navHomeRv.models = it
        if (!viewModel.feedsObserveData.value.isNullOrEmpty()) {
            if (viewModel.pageIndex == 1) {
                feedsAdapter.notifyDataSetChanged()
            } else {
                feedsAdapter.notifyItemRangeChanged(
                    viewModel.lastFeedsSize - 1,
                    it.size
                )
            }
        }
        viewModel.lastFeedsSize = it.size
        if (viewModel.pageIndex == 1) {
            //下拉刷新关闭动画在PartSkeleton里

//                判断是否需要自动加载更多
//                if (viewBinding.navHomeRv.models?.get(0) is RvNoDataEntry
//                    || viewBinding.navHomeRv.models?.get(0) is RvSkeletonEntry
//                ) {
//                    viewBinding.page.setEnableAutoLoadMore(false)
//                } else {
//                    viewBinding.page.setEnableAutoLoadMore(true)
//                }
        } else {
            if (viewBinding.page.isLoading) {
                viewBinding.page.finishLoadMore()
            }
        }
    }

    fun handleVM(
        mActivity: FragmentActivity
    ) {
        layoutManager =
            viewBinding.navHomeRv.bindProductFeeds(feedsAdapter) as StaggeredGridLayoutManager?
        viewBinding.navHomeRv.itemAnimator = FadeInAnimator()
        viewBinding.navHomeRv.isNestedScrollingEnabled = true

        autoPlayPostVideo2(
            mActivity,
            layoutManager,
            viewBinding.navHomeRv,
            R.id.home_video_player
        )
    }


    private fun handleFeedsClick(md: RvFeedsProductBean, position: Int) {
        //插入策略
        //请求过一次 不再请求
        if (viewModel.hasInsertVaneOrBrandColl[position] == true) {
            return
        }
        //倒数2个 不插入
        if (position == viewModel.feedsObserveData.value!!.size - 1 || position == viewModel.feedsObserveData.value!!.size - 2) {
            toastShowDev("倒数2个 不插入", viewModel.showToastDev2)
            return
        }
        //风向标和商品集合不能挨着
        if (viewModel.feedsObserveData.value!![position + 1] is RvFeedsWeatherVaneBean
            || viewModel.feedsObserveData.value!![position + 1] is RvFeedsBrandCollBean
            || viewModel.feedsObserveData.value!![position + 2] is RvFeedsWeatherVaneBean
            || viewModel.feedsObserveData.value!![position + 2] is RvFeedsBrandCollBean
        ) {
            toastShowDev("风向标和商品集合不能挨着", viewModel.showToastDev2)
            return
        }

        viewModel.vaneOrBrand(
            md.product.productF.productId,
            md.product.productF.standardSpuIds,
            md.product.productF.hotBrand?.name,
            position,
        ) {
            toastShowDev("执行风向标 商品集合的插入动画", viewModel.showToastDev2)
            /***
             * 执行风向标 商品集合的插入动画
             * index 插入到[models]指定位置, 如果index超过[models]长度则会添加到最后
             */
//                                viewBinding.navHomeRv.addModels(listOf(insertData), index = p+1)
            feedsAdapter.notifyItemRangeChanged(
                position,
                viewModel.lastFeedsSize
            )
        }
    }

    var scrollCalculatorHelper: ScrollCalculatorHelper2Home? = null
    private fun autoPlayPostVideo2(
        activity: FragmentActivity,
        layoutManager: StaggeredGridLayoutManager?,
        rv: RecyclerView,
        viewId: Int
    ) {
        //限定范围为屏幕一半的上下偏移200
        val playTop = screenHeight / 2 - AutoSizeUtils.dp2px(200f)
        val playBottom = screenHeight / 2 + AutoSizeUtils.dp2px(200f)
        //自动播放帮助类
        scrollCalculatorHelper =
            ScrollCalculatorHelper2Home(
                activity,
                activity.lifecycle,
                viewId,
                playTop,
                playBottom
            )

        rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var firstVisibleItem = 0
            var lastVisibleItem = 0
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                scrollCalculatorHelper?.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val positions =
                    layoutManager!!.findFirstVisibleItemPositions(null)
                if (positions != null && positions.isNotEmpty()) {
                    firstVisibleItem = positions[0]
                }
                val positions2 =
                    layoutManager!!.findLastVisibleItemPositions(null)
                if (positions2 != null && positions2.isNotEmpty()) {
                    lastVisibleItem = positions2[positions2.size - 1]
                }

                //这是滑动自动播放的代码
                scrollCalculatorHelper?.onScroll(
                    recyclerView,
                    firstVisibleItem,
                    lastVisibleItem,
                    lastVisibleItem - firstVisibleItem
                )
            }
        })
    }

}